//
//  SWMultiMealView.m
//  YiYueHairdresser
//
//  Created by Sky on 2018/10/29.
//  Copyright © 2018年 YuYiLian. All rights reserved.
//

#import "SWMultiMealView.h"
#import "SWProjectCell.h"
#import "SWProjectListView.h"
#import "STTimerSelView.h"

@interface SWMultiMealView()<UITableViewDelegate, UITableViewDataSource, STTimerSelViewDelegate,UITextFieldDelegate>
{
    STTimerSelView * timerSelView;
    NSArray * arrSelTimers;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong)  NSArray <NSArray *>*titleArray;
@property (nonatomic, strong)  NSArray < NSString*> *numArray;  //中文123456789
@property (nonatomic, strong) UITextField *nameField;
@property (nonatomic, strong) UITextField *costField;
@property (nonatomic, strong) UITextField *priceField;
@property (nonatomic, strong) UITextField *timeField;
@property (nonatomic, strong) UIButton *saveBtn;            //保存
@end

@implementation SWMultiMealView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        [self initUI];
    }
    return self;
}

#pragma mark - 初始化UI
- (void)initUI {
    
    [self addSubview:self.tableView];
    [self addSubview:self.saveBtn];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.inset(0);
        make.bottom.equalTo(self.saveBtn.mas_top);
    }];
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.inset(0);
        make.height.mas_equalTo(50);
    }];
}


-(void)reloadMultiTableView{
    [_tableView reloadData];
}

-(void)serSerSelTimer{
    arrSelTimers = @[@"0.5小时",@"1小时",@"1.5小时",@"2小时",@"2.5小时",@"3小时",@"3.5小时",@"4小时",@"4.5小时",@"5小时",@"5.5小时",@"6小时"];
    if (!timerSelView) {
        timerSelView = [[STTimerSelView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        timerSelView.delegate = self;
        [timerSelView setTimerSelectWithData:arrSelTimers];
    }
    [self addSubview:timerSelView];
}

-(void)serActualSerSelTimer:(NSInteger)num{
    STTimerSelView * actualTimerSelView = [[STTimerSelView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    //TODO:实际服务时间可以多选，开始和结束必选
    actualTimerSelView.delegate = self;
    actualTimerSelView.isMulti = YES;
    actualTimerSelView.selNums = [NSMutableArray arrayWithArray:@[@0,@(num)]];
    actualTimerSelView.unAbles = @[@0,@(num)];
    actualTimerSelView.titleStr = @"实际服务时间";
    [actualTimerSelView setTimerSelectWithData:[arrSelTimers subarrayWithRange:NSMakeRange(0, num+1)]];
    [self addSubview:actualTimerSelView];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.titleArray.count;
    }
    return self.serviceModel.packageOptions.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
        return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 50;
    }
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (section == 1) {
        return 50;
    }
    return 0.001;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * addView = [[UIView alloc]init];
    if (section == 1) {
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        addBtn.frame = CGRectMake(13, 5, 80, 30);
        [addBtn setTitle:@"+ 添加服务" forState:UIControlStateNormal];
        [addBtn setTitleColor:UIColor.grayColor forState:UIControlStateNormal];
        addBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        addBtn.backgroundColor = UIColor.whiteColor;
        addBtn.layer.masksToBounds = YES;
        addBtn.layer.cornerRadius = 3;
        [addBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        [addView addSubview:addBtn];
    }
    return addView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * headerView = [UIView new];
    headerView.backgroundColor = [UIColor clearColor];
    if (section == 1) {
        
        UILabel * nameLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 200, 50)];
        nameLab.font = FONT(16);
        nameLab.textColor = [UIColor lightGrayColor];
        nameLab.text = @"套餐包含服务内容";
        [headerView addSubview:nameLab];
    }
    
    return headerView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     UITableViewCell *cell;
    if (indexPath.section == 0) {
       
        cell = [[NSBundle mainBundle] loadNibNamed:@"STTextCell" owner:nil options:nil].lastObject;
        UILabel * nameLab = (UILabel *)[cell viewWithTag:11001];
        UIView * line = (UIView *)[cell viewWithTag:11003];
        nameLab.text = self.titleArray[indexPath.row][0];
        if (indexPath.section ==0) {
            if (indexPath.row==0) {
                _nameField = (UITextField *)[cell viewWithTag:11002];
                _nameField.placeholder = self.titleArray[indexPath.row][1];
                _nameField.text =self.serviceModel.servicename;
                _nameField.delegate = self;
            }else if (indexPath.row==1) {
                _costField = (UITextField *)[cell viewWithTag:11002];
                _costField.placeholder = self.titleArray[indexPath.row][1];
                _costField.delegate = self;
                if(self.serviceModel.costprice){
                    _costField.text = [NSString stringWithFormat:@"%0.2f",self.serviceModel.costprice];
                }
                    
            }else if (indexPath.row==2) {
                _priceField = (UITextField *)[cell viewWithTag:11002];
                _priceField.placeholder = self.titleArray[indexPath.row][1];
                _priceField.delegate = self;
                if(self.serviceModel.price){
                    _priceField.text= [NSString stringWithFormat:@"%0.2f",self.serviceModel.price];
                }
            }else if (indexPath.row==3) {
                _timeField = (UITextField *)[cell viewWithTag:11002];
                _timeField.placeholder = self.titleArray[indexPath.row][1];
                _timeField.delegate = self;
                _timeField.enabled = NO;
                if(self.serviceModel.duration){
                    _timeField.text = [NSString stringWithFormat:@"%0.1f小时",self.serviceModel.duration/60.0];
                }
            }
        }
    
        if (indexPath.row == self.titleArray.count -1) {
            line.hidden = YES;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else {
            line.hidden = NO;
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
       
        cell.selectionStyle= UITableViewCellSelectionStyleNone;
        return cell;
    }else if(indexPath.section ==1){
        SWProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SWProjectCell"];
        cell.selectTextField.tag = indexPath.row;
        cell.inputField.tag = 19000+indexPath.row;
        cell.selectTextField.delegate = self;
        cell.inputField.delegate = self;
        STServiceOptionModel * dict = self.serviceModel.packageOptions[indexPath.row];
        [cell setProjectCellData:dict withArrServices:self.arrServiceType];
        cell.titleLab.text = [NSString stringWithFormat:@"项目%@",self.numArray[indexPath.row]];
        return cell;
    }else{
         cell = [[NSBundle mainBundle] loadNibNamed:@"STTextCell" owner:nil options:nil].lastObject;
        return cell;
    }
    return nil;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    //第二组可以左滑删除
    if (indexPath.section == 1) {
        return YES;
    }
    return NO;
}

// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (indexPath.section == 1) {
            [self.serviceModel.packageOptions removeObjectAtIndex:indexPath.row];
            [tableView reloadSection:1 withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.titleArray.count - 1 == indexPath.row && indexPath.section == 0) {
        [self serSerSelTimer];
    }
}

#pragma mark - STTimerSelViewDelegate

-(void)timerSelView:(STTimerSelView *)view  SeltectNum:(NSArray *)num{
    if(!num.count){
        return;
    }
    if([view isEqual:timerSelView]){
        int selNum = (int)[num.firstObject integerValue];
        NSString * selStr = arrSelTimers[selNum];
        NSString * timerStr = [selStr substringToIndex:(selStr.length-2)];
        self.serviceModel.duration =[timerStr floatValue]*60;
        if(selNum>=2){
            [self serActualSerSelTimer:selNum];
        }
        [self.tableView reloadRow:3 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    }else{
        NSMutableArray * arrTimer = [NSMutableArray arrayWithCapacity:num.count];
        for (NSString * selNumStr in num) {
            int selNum = (int)[selNumStr integerValue];
            NSString * selStr = arrSelTimers[selNum];
            NSString * timerStr = [selStr substringToIndex:(selStr.length-2)];
            [arrTimer addObject:timerStr];
        }
        NSString * lockStr = [arrTimer componentsJoinedByString:@","];
        self.serviceModel.locktime = lockStr;
    }
    
}


#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if(textField.text.length){
        if ([textField isEqual:self.nameField]) {
            self.serviceModel.servicename =self.nameField.text;
        } else if ([textField isEqual:self.costField]) {
            self.serviceModel.costprice =[self.costField.text floatValue];
        }else if ([textField isEqual:self.priceField]) {
            self.serviceModel.price =[self.priceField.text floatValue];
        }else{
            if (textField.tag>=19000) {
                STServiceOptionModel * optionModel = self.serviceModel.packageOptions[textField.tag-19000];
                optionModel.optionvalue = textField.text;
                STServiceOOModel * oomodel = optionModel.pakageOptionDetails.firstObject;
                oomodel.optionvalue = textField.text;
            }
        }
    }
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if([textField isEqual:_nameField] || [textField isEqual:_costField]|| [textField isEqual:_priceField]||textField.tag>=19000){
        return YES;
    }
    [self selectTextField:textField];
    return NO;
}


#pragma mark - 点击事件
- (void)selectTextField:(UITextField *)textField{
    
    
    SWProjectCell *cell = (SWProjectCell *)textField.superview.superview;
    NSIndexPath *indexPath =  [self.tableView indexPathForCell:cell];
    CGRect rect = [self.tableView convertRect:[self.tableView rectForRowAtIndexPath:indexPath] toView:[self.tableView superview]];
    CGFloat y = CGRectGetMaxY(textField.frame);
    CGFloat ma_Y = CGRectGetMaxY(rect);
    CGRect frame = CGRectMake(textField.mj_x, ma_Y + y-44, 100, 200);
    SWProjectListView *listView  = [[SWProjectListView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    listView.listFrame = frame;
    listView.titleArray = self.arrServiceType;
    [listView showView];

    listView.SelectBackBlock = ^(int selNum) {
        STServiceOptionModel * optionModel = self.serviceModel.packageOptions[textField.tag];
        STServiceCategoryModel * model = self.arrServiceType[selNum];
        textField.text = model.name;
        if(model.options.count){
            STServiceOptionModel * optionModel = model.options.firstObject;
            cell.titleBLab.hidden = NO;
            cell.inputField.hidden = NO;
            cell.titleBLab.text = optionModel.optionname;
            cell.inputField.text =optionModel.optionvalue;
        }else{
            cell.titleBLab.hidden = YES;
            cell.inputField.hidden = YES;
        }
        STServiceOptionModel * optionDetail =model.options.firstObject;
        optionModel.optionId =optionDetail.objectId;
        optionModel.optionname = model.name;
        optionModel.categoryId =model.objectId;
        NSLog(@"");
    };
}

- (void)clickAction:(UIButton *)sender {
    STServiceOptionModel * model = [STServiceOptionModel new];
    model.optiontitle = @"";
    model.optionvalue = @"";
    model.optionname = @"";
    if(!self.serviceModel.packageOptions){
        self.serviceModel.packageOptions = ( NSMutableArray<STServiceOptionModel> * )[NSMutableArray arrayWithCapacity:0];
    }
    [self.serviceModel.packageOptions addObject:model];
    [self.tableView reloadData];
}

-(void)saveAction{
    if(!_serviceModel.servicename.length){
        
    }else if(!_serviceModel.price){
        
    }else if(!_serviceModel.duration){
        
    }else if(!_serviceModel.packageOptions.count){
        
    } 
    self.saveBtnAction(self.serviceModel);
}

#pragma mark - 懒加载
-(UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [UITableView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UIColor.groupTableViewBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"SWProjectCell" bundle:nil] forCellReuseIdentifier:@"SWProjectCell"];
    }
    return _tableView;
}

-(UIButton *)saveBtn {
    if (_saveBtn == nil) {
        _saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_saveBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_saveBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _saveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _saveBtn.backgroundColor = UIColor.orangeColor;
        [_saveBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}



-(NSArray<NSArray *> *)titleArray {
    if (_titleArray == nil) {
        
        _titleArray = @[@[@"套餐名称：", @"请输入套餐名称"],@[@"套餐原价：", @"请输入价格"], @[@"套餐价格：", @"请输入价格"], @[@"服务所需时间：", @" "]];
    }
    return _titleArray;
}


- (NSArray<NSString *> *)numArray {
    if (_numArray == nil) {
        _numArray = @[@"一", @"二", @"三",@"四",@"五",@"六",@"七",@"八",@"九", @"十"];
    }
    return _numArray;
}

@end
